package com.example.baseutils.usb;

import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.util.Log;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Usb工具
 */
public class UsbUtils {

    /**
     * 判断某usb设备是否摄像头，usb摄像头的大小类是239-2
     *
     * @param usbDevice
     * @return
     */
    public static boolean isUsbCamera(UsbDevice usbDevice) {
        return usbDevice != null && 239 == usbDevice.getDeviceClass() && 2 == usbDevice.getDeviceSubclass();
    }

    /**
     * 获取usb摄像头设备
     *
     * @return
     */
    public static ArrayList<UsbDevice> getUsbCameraDevice(Context context) {
        UsbManager mUsbManager = (UsbManager) context.getSystemService(context.USB_SERVICE);
        HashMap<String, UsbDevice> deviceMap = mUsbManager.getDeviceList();
        ArrayList<UsbDevice> devices = new ArrayList<>();
        if (deviceMap != null) {
            for (UsbDevice usbDevice : deviceMap.values()) {
//                Log.i("UsbDevice", "getUsbCameraDevice: " + usbDevice.toString());
                if (isUsbCamera(usbDevice)) {
                    Log.i("UsbDevice", "add: " + usbDevice.hashCode());
                    devices.add(usbDevice);
                }
            }
        }
        return devices;
    }
}
